import re
import time
from datetime import datetime, timedelta

from playwright.sync_api import Playwright, sync_playwright, expect

from tools.entity import Trade
from tools.dbTool import dbTool

startDate = "2024-11-19"  # 不要前置0


def wait(seconds=None):
    if seconds is None:  # 随机2-5秒
        seconds = 2 + int(4 * (time.time() % 1))
    time.sleep(seconds)


def wait_for_text(page, text, timeout=300000):
    """Wait for specific text to appear on the page."""
    page.wait_for_selector(f"text={text}", timeout=timeout)


def getEndDateInfo():
    # 当前-1天
    endDate = datetime.now().date() - timedelta(days=1)
    return endDate.strftime("%Y-%m-%d"), endDate.year, endDate.month, endDate.day


def run(playwright: Playwright) -> None:
    endDate, endYear, endMonth, endDay = getEndDateInfo()
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context(storage_state="jq.json")
    page = context.new_page()
    page.goto("https://www.joinquant.com/algorithm/index/list")

    wait()
    strategy = "让利润自由奔腾策略-10W-Clone"
    with page.expect_popup() as page1_info:
        page.get_by_role("link", name=strategy).click()
    wait()
    page1 = page1_info.value
    if page1.get_by_role("link", name="跳过").count() != 0:
        page1.get_by_role("link", name="跳过").click()
        wait()
        page1.get_by_text("不再提示").click()
        wait()
    wait()
    # 选择开始时间
    page1.locator("#startTime").click()
    startDateArr = startDate.split("-")
    page1.get_by_role("combobox").nth(1).select_option(startDateArr[0])
    # page1.locator("#startTime").select_option("2024")
    page1.get_by_role("combobox").nth(2).select_option(str(int(startDateArr[1]) - 1))  # 当前月份减1
    # page1.locator("#startTime").select_option("5")
    page1.get_by_role("link", name=startDateArr[2], exact=True).click()
    wait()
    # 选择结束时间
    page1.locator("#endTime").click()
    page1.get_by_role("combobox").nth(1).select_option(str(endYear))
    page1.get_by_role("combobox").nth(2).select_option(str(endMonth - 1))
    page1.get_by_role("link", name=str(endDay), exact=True).click()
    page1.locator("#daily_backtest_capital_base_box").fill("20000")
    # page1.locator("#daily_backtest_capital_base_box").press("Enter")
    wait()
    # 运行回测
    page1.get_by_text("运行回测", exact=True).click()
    # wait(60)
    wait_for_text(page1, "回测完成")
    wait()
    # page1.get_by_role("link", name="回测详情").click()
    # wait()
    page1.get_by_role("link", name="交易详情").click()
    wait()
    trElements = page1.query_selector_all("#table-transactioninfo tr")
    for tr in trElements:
        tds = tr.inner_text().split('\t')
        if len(tds) <= 3:
            continue
        if tds[0] != endDate:  # endDate
        # if tds[0] != "2024-11-05":
            continue
        # ['2024-05-07', '10:00:00', '美芝股份(002856.XSHE)', '买', '市价单', '4200股', '7.79', '32,718.00', '0.00', '8.18']
        print(f"时间: {tds[0]}, 标的: {tds[2]}, 价格: {tds[6]}, 数量: {int(tds[5].replace('股', ''))}")
        # 保存到数据库
        trade = Trade(code=tds[2], amount=int(tds[5].replace('股', '')), date=tds[0], price=float(tds[6]),
                      strategy=strategy)
        dbTool.save(trade)
    wait()
    # ---------------------
    context.storage_state(path="jq.json")
    context.close()
    browser.close()


def getTrade():
    print("开始获取交易信息")
    with sync_playwright() as playwright:
        run(playwright)
    print("结束获取交易信息")


if __name__ == "__main__":
    getTrade()
